import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { 
  User, 
  Phone, 
  Mail, 
  Camera, 
  Save,
  Package,
  Heart,
  MapPin,
  Settings
} from 'lucide-react';
import { profileApi, orderApi } from '@/db/api';
import { useAuth } from 'miaoda-auth-react';
import type { Profile, Order } from '@/types/types';
import { toast } from 'sonner';

const ProfilePage: React.FC = () => {
  const navigate = useNavigate();
  const { user, logout } = useAuth();
  
  const [profile, setProfile] = useState<Profile | null>(null);
  const [recentOrders, setRecentOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  
  const [formData, setFormData] = useState({
    nickname: '',
    avatar_url: ''
  });

  useEffect(() => {
    if (!user) {
      navigate('/login');
      return;
    }
    loadData();
  }, [user, navigate]);

  const loadData = async () => {
    try {
      setLoading(true);
      const [profileData, ordersData] = await Promise.all([
        profileApi.getCurrentProfile(),
        orderApi.getUserOrders()
      ]);
      
      if (profileData) {
        setProfile(profileData);
        setFormData({
          nickname: profileData.nickname || '',
          avatar_url: profileData.avatar_url || ''
        });
      }
      
      setRecentOrders(ordersData.slice(0, 5));
    } catch (error) {
      console.error('加载数据失败:', error);
      toast.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSaveProfile = async () => {
    try {
      setSaving(true);
      const updatedProfile = await profileApi.updateProfile(formData);
      setProfile(updatedProfile);
      toast.success('个人信息已更新');
    } catch (error) {
      console.error('更新个人信息失败:', error);
      toast.error('更新个人信息失败');
    } finally {
      setSaving(false);
    }
  };

  const handleLogout = async () => {
    await logout();
    navigate('/');
  };

  const getStatusBadge = (status: Order['status']) => {
    const statusMap = {
      pending: { label: '待付款', color: 'bg-yellow-100 text-yellow-800' },
      paid: { label: '已付款', color: 'bg-blue-100 text-blue-800' },
      shipped: { label: '已发货', color: 'bg-purple-100 text-purple-800' },
      delivered: { label: '已完成', color: 'bg-green-100 text-green-800' },
      cancelled: { label: '已取消', color: 'bg-red-100 text-red-800' }
    };
    
    const info = statusMap[status] || { label: '未知', color: 'bg-gray-100 text-gray-800' };
    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${info.color}`}>
        {info.label}
      </span>
    );
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-pink-600"></div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-4">个人中心</h1>
          <p className="text-gray-600">管理您的个人信息和订单</p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          {/* Profile Sidebar */}
          <div className="lg:col-span-1">
            <Card>
              <CardContent className="p-6 text-center">
                <Avatar className="w-24 h-24 mx-auto mb-4">
                  <AvatarImage src={profile?.avatar_url} />
                  <AvatarFallback className="text-2xl">
                    {profile?.nickname?.[0] || profile?.phone?.[0] || 'U'}
                  </AvatarFallback>
                </Avatar>
                
                <h2 className="text-xl font-semibold text-gray-900 mb-2">
                  {profile?.nickname || '未设置昵称'}
                </h2>
                
                <p className="text-gray-600 mb-4">
                  {profile?.phone}
                </p>
                
                <div className="space-y-2">
                  <Button 
                    variant="outline" 
                    size="sm" 
                    className="w-full"
                    onClick={() => navigate('/orders')}
                  >
                    <Package className="h-4 w-4 mr-2" />
                    我的订单
                  </Button>
                  
                  <Button 
                    variant="outline" 
                    size="sm" 
                    className="w-full"
                  >
                    <Heart className="h-4 w-4 mr-2" />
                    我的收藏
                  </Button>
                  
                  <Button 
                    variant="outline" 
                    size="sm" 
                    className="w-full"
                  >
                    <MapPin className="h-4 w-4 mr-2" />
                    收货地址
                  </Button>
                  
                  {profile?.role === 'admin' && (
                    <Button 
                      variant="outline" 
                      size="sm" 
                      className="w-full"
                      onClick={() => navigate('/admin')}
                    >
                      <Settings className="h-4 w-4 mr-2" />
                      管理后台
                    </Button>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Main Content */}
          <div className="lg:col-span-3">
            <Tabs defaultValue="profile" className="space-y-6">
              <TabsList className="grid w-full grid-cols-3">
                <TabsTrigger value="profile">个人信息</TabsTrigger>
                <TabsTrigger value="orders">最近订单</TabsTrigger>
                <TabsTrigger value="settings">账户设置</TabsTrigger>
              </TabsList>

              {/* Profile Tab */}
              <TabsContent value="profile">
                <Card>
                  <CardHeader>
                    <CardTitle>个人信息</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-6">
                    <div className="flex items-center gap-6">
                      <Avatar className="w-20 h-20">
                        <AvatarImage src={formData.avatar_url} />
                        <AvatarFallback className="text-xl">
                          {formData.nickname?.[0] || profile?.phone?.[0] || 'U'}
                        </AvatarFallback>
                      </Avatar>
                      <div>
                        <Button variant="outline" size="sm">
                          <Camera className="h-4 w-4 mr-2" />
                          更换头像
                        </Button>
                        <p className="text-sm text-gray-500 mt-2">
                          支持 JPG、PNG 格式，文件大小不超过 2MB
                        </p>
                      </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <div>
                        <Label htmlFor="nickname">昵称</Label>
                        <Input
                          id="nickname"
                          value={formData.nickname}
                          onChange={(e) => setFormData(prev => ({ ...prev, nickname: e.target.value }))}
                          placeholder="请输入昵称"
                        />
                      </div>
                      
                      <div>
                        <Label htmlFor="phone">手机号</Label>
                        <Input
                          id="phone"
                          value={profile?.phone || ''}
                          disabled
                          className="bg-gray-50"
                        />
                      </div>
                      
                      <div>
                        <Label htmlFor="role">用户角色</Label>
                        <Input
                          id="role"
                          value={profile?.role === 'admin' ? '管理员' : '普通用户'}
                          disabled
                          className="bg-gray-50"
                        />
                      </div>
                      
                      <div>
                        <Label htmlFor="created_at">注册时间</Label>
                        <Input
                          id="created_at"
                          value={profile ? new Date(profile.created_at).toLocaleDateString() : ''}
                          disabled
                          className="bg-gray-50"
                        />
                      </div>
                    </div>

                    <div className="flex justify-end">
                      <Button 
                        onClick={handleSaveProfile}
                        disabled={saving}
                        className="bg-pink-600 hover:bg-pink-700"
                      >
                        <Save className="h-4 w-4 mr-2" />
                        {saving ? '保存中...' : '保存更改'}
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              {/* Orders Tab */}
              <TabsContent value="orders">
                <Card>
                  <CardHeader>
                    <CardTitle>最近订单</CardTitle>
                  </CardHeader>
                  <CardContent>
                    {recentOrders.length === 0 ? (
                      <div className="text-center py-8">
                        <Package className="h-16 w-16 text-gray-300 mx-auto mb-4" />
                        <p className="text-gray-500">暂无订单记录</p>
                        <Button 
                          className="mt-4"
                          onClick={() => navigate('/products')}
                        >
                          去购物
                        </Button>
                      </div>
                    ) : (
                      <div className="space-y-4">
                        {recentOrders.map((order) => (
                          <div 
                            key={order.id}
                            className="border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer"
                            onClick={() => navigate(`/orders/${order.id}`)}
                          >
                            <div className="flex items-center justify-between mb-2">
                              <div className="font-medium">
                                订单号: {order.order_number}
                              </div>
                              {getStatusBadge(order.status)}
                            </div>
                            
                            <div className="text-sm text-gray-600 mb-2">
                              下单时间: {new Date(order.created_at).toLocaleString()}
                            </div>
                            
                            <div className="flex items-center justify-between">
                              <div className="text-sm text-gray-600">
                                共 {order.order_items?.reduce((sum, item) => sum + item.quantity, 0)} 件商品
                              </div>
                              <div className="font-semibold text-pink-600">
                                ¥{order.total_amount.toFixed(2)}
                              </div>
                            </div>
                          </div>
                        ))}
                        
                        <div className="text-center pt-4">
                          <Button 
                            variant="outline"
                            onClick={() => navigate('/orders')}
                          >
                            查看全部订单
                          </Button>
                        </div>
                      </div>
                    )}
                  </CardContent>
                </Card>
              </TabsContent>

              {/* Settings Tab */}
              <TabsContent value="settings">
                <Card>
                  <CardHeader>
                    <CardTitle>账户设置</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-6">
                    <div className="space-y-4">
                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div>
                          <h3 className="font-medium">修改密码</h3>
                          <p className="text-sm text-gray-500">定期更换密码以保护账户安全</p>
                        </div>
                        <Button variant="outline" size="sm">
                          修改
                        </Button>
                      </div>
                      
                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div>
                          <h3 className="font-medium">绑定邮箱</h3>
                          <p className="text-sm text-gray-500">绑定邮箱用于接收重要通知</p>
                        </div>
                        <Button variant="outline" size="sm">
                          绑定
                        </Button>
                      </div>
                      
                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div>
                          <h3 className="font-medium">隐私设置</h3>
                          <p className="text-sm text-gray-500">管理您的隐私和数据使用偏好</p>
                        </div>
                        <Button variant="outline" size="sm">
                          设置
                        </Button>
                      </div>
                    </div>

                    <div className="pt-6 border-t">
                      <Button 
                        variant="destructive" 
                        onClick={handleLogout}
                        className="w-full"
                      >
                        退出登录
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ProfilePage;